/*
 * frequency_driver.h
 *
 * Created: 2014-01-14 16:41:12
 *  Author: Johan
 */ 

#include <stdbool.h>
#ifndef FREQUENCY_DRIVER_H_
#define FREQUENCY_DRIVER_H_

 /*If this #define is set to '1',the 32 bit frequency counter option is enabled using TCCC.
 Otherwise the 16-bit result will be available using TCCB */

#define F_CPU 2000000UL

#define SENSOR_0 	EVSYS_CHMUX_PORTD_PIN0_gc
#define SENSOR_1 	EVSYS_CHMUX_PORTD_PIN1_gc
#define SENSOR_2 	EVSYS_CHMUX_PORTD_PIN2_gc
#define SENSOR_3 	EVSYS_CHMUX_PORTD_PIN3_gc

/*Defines to make it more readable, renaming the timers to A and B */
#define TCCA	TCC0
#define TCCB	TCC1

#define TCCA_INTFLAGS	TCC0_INTFLAGS
#define TCCB_INTFLAGS	TCC1_INTFLAGS

#define	TCCA_OVFIF_bm	TC0_OVFIF_bm
#define TCCB_OVFIF_bm	TC1_OVFIF_bp

#define TCCA_OVF_vect 	TCC0_OVF_vect


#define TCCA_CNT_TO_OVF	 		(0xffffUL)-(F_CPU/(8UL*4UL))
#define TCCA_CNT_TO_OVF_L 		(TCCA_CNT_TO_OVF) & (0xff)
#define TCCA_CNT_TO_OVF_H 		(TCCA_CNT_TO_OVF) >> 8

#define EVENT_SYSTEM_INPUT_PIN	EVSYS_CHMUX_PORTD_PIN0_gc
#define EVSYS_CHMUX_TCCA_OVF_gc	EVSYS_CHMUX_TCC0_OVF_gc
#define EVSYS_CHMUX_TCCB_OVF_gc	EVSYS_CHMUX_TCC1_OVF_gc

#define TCA_EVAVT_gm	TC0_EVACT_gm
#define	TCA_EVACT0_bm	TC0_EVACT0_bm
#define	TCA_EVSEL_gm	TC0_EVSEL_gm
#define	TCA_EVSEL3_bm	TC0_EVSEL3_bm
#define	TCA_EVSEL0_bm	TC0_EVSEL0_bm

#define TCB_EVAVT_gm	TC1_EVACT_gm
#define	TCB_EVACT0_bm	TC1_EVACT0_bm
#define	TCB_EVSEL_gm	TC1_EVSEL_gm
#define	TCB_EVSEL3_bm	TC1_EVSEL3_bm
#define	TCB_EVSEL0_bm	TC1_EVSEL0_bm

#define	TCB_CCAEN_bm	TC1_CCAEN_bm
int active_sensor;
bool reading_complete;

/* Initialization of counters and event system */

void init_frequency(void);


/* Function to start measuring frequency via the Event System after TCC0 and TCC1 have been initialized */

void start_frequency_measurement(void);
 
/* Used to change the active sensor that is being read from */
void set_active_sensor(int);

int get_frequency_result(void); 
void clear_frequency_result(void);





#endif /* FREQUENCY_DRIVER_H_ */